
package com.kugou.game.sdk.ui.fragment;

import java.util.ArrayList;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.Html;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kugou.game.sdk.adapter.RechargeMoneyGridAdapter;
import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.core.PayManager;
import com.kugou.game.sdk.core.SDKActions;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.entity.KubiPayRequestParams;
import com.kugou.game.sdk.entity.PayConstant.ChargeIndexMode;
import com.kugou.game.sdk.entity.PayConstant.ChargeType;
import com.kugou.game.sdk.interfaces.OnKubiPayListener;
import com.kugou.game.sdk.protocol.CheckPayPasswdStateTask;
import com.kugou.game.sdk.protocol.CheckPayPasswdStateTask.CheckPayPswStateResponse;
import com.kugou.game.sdk.ui.activity.NotEnoughKubiRechargeActivity;
import com.kugou.game.sdk.ui.activity.RechargeActivity;
import com.kugou.game.sdk.ui.dialog.BaseConfirmDialog;
import com.kugou.game.sdk.ui.dialog.InputPayPasswdDialog;
import com.kugou.game.sdk.ui.dialog.InputPayPasswdDialog.OnPasswordChangedListener;
import com.kugou.game.sdk.utils.AppUtil;
import com.kugou.game.sdk.utils.NetWorkUtil;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ToastUtil;

/**
 * 描述:游币支付
 *
 * @author wcj
 * @since 2015年11月11日 下午5:38:26
 */
public class RechargeByKuBiFragment extends BaseRechargeFragment {

    private final static int KUBI_RECHARGE_REQUEST_CODE = 1000;

    private final static int NO_KUBI_RECHARGE_REQUEST_CODE = 1001;

    public static final int NO_KUBI_RECHARGE_RESPONDE_CODE = 1002;

    public static final String YOUXIBI = "youxibi";

    /**
     * 请求支付
     */
    private static final int MSG_BACK_REQUEST_PAY = 1;

    /**
     * 请求游币支付成功
     */
    private static final int MSG_KUBIPAY_SUCCESS = 2;

    /**
     * 请求游币支付失败
     */
    private static final int MSG_KUBIPAY_FAILED = 3;

    private static final int MSG_KUBIPAY_ING = 4;

    // 请求支付密码状态
    private static final int MSG_REQUEST_PAY_STATUES = 5;

    private static final int MSG_REQUEST_PAY_STATUES_SUCCESS = 6;

    private static final int MSG_REQUEST_PAY_STATUES_FAILED = 7;

    private static final int[] sMoneys = {
            10, 20, 30, 50, 100, 200
    };

    private Context mContext;

    private TextView mYoubiTextView;

    private EditText mInputOtherValueEditText;

    private LinearLayout mOtherValueLayout;

    // 普通充值，选择游币数量的框View
    private View mRechargeContent;

    // 普通充值，选择游币数量的框
    private GridView mGridView;

    // 确认兑换按钮
    private Button mSubmitRechargeBtn;

    // 底部充值游币入口
    private TextView mRechargeKubiBtn;

    // 当前充值游币数量
    private int mRechargeValue = 0;

    // 当前拥有的游币数量
    private float mAccountKubiNumber = 0;

    // 游币选择适配器
    private RechargeMoneyGridAdapter mRechargeAdapter;

    // 定额数量 同时作为判断时候是否定额支付
    private int mFixedMoneyNum = -1;

    private String mOrderid = "";

    private InputPayPasswdDialog mInputPayPasswdDialog;

    // 游币充值入口，当有充值优惠信息的时候显示，否则隐藏此入口
    private RelativeLayout mKubiRechargeLayout;

    public int getFixedMoneyNum() {
        return mFixedMoneyNum;
    }

    public void setFixedMoneyNum(int fixedMoneyNum) {
        this.mFixedMoneyNum = fixedMoneyNum;
        if (fixedMoneyNum > 0) {
            mRechargeValue = fixedMoneyNum * PayManager.getYoubiRatio();
        }
    }

    /**
     * 获取fragment实例
     * 
     * @param fixedMoneyNum 定额数量
     * @return
     */
    public static RechargeByKuBiFragment getFragment(int fixedMoneyNum) {
        RechargeByKuBiFragment fragment = new RechargeByKuBiFragment();
        fragment.setFixedMoneyNum(fixedMoneyNum);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContext = getActivity();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        User user = UserManager.getInstance().getCurrentUserInternal();
        mAccountKubiNumber = user.getKubiNum();
        if (mAccountKubiNumber < 0) {
            mAccountKubiNumber = 0;
        }

        initViews();
        initCoupon();
        updateView();
        setKubiValueTextView();
    }

    @Override
    public void setupActions(ArrayList<String> actions) {
        super.setupActions(actions);
        actions.add(SDKActions.ACTION_YOUBI_RATIO_CHANGE);
    }

    @Override
    public void handleBroadcast(Context context, Intent intent) {
        super.handleBroadcast(context, intent);
        String action = intent.getAction();
        // 当游币充值优惠信息发生变化的时候，下方入口刷新
        if (action.equals(SDKActions.ACTION_YOUBI_RATIO_CHANGE) && mKubiRechargeLayout != null
                && mRechargeKubiBtn != null) {
            if (!PayManager.hasYoubiRechargepreferential()) {
                mKubiRechargeLayout.setVisibility(View.GONE);
            } else {
                mKubiRechargeLayout.setVisibility(View.VISIBLE);
                mRechargeKubiBtn.setText(PayManager.getKubiRechargePreferentialSubTitle());
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        int layoutId = Rx.layout.kg_fragment_recharge_kubi;
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            layoutId = Rx.layout.kg_fragment_recharge_kubi_land;
        }
        return inflater.inflate(layoutId, null);
    }

    private void initViews() {

        mYoubiTextView = (TextView) findViewById(Rx.id.kg_common_tips_bar_youbi);
        mYoubiTextView.setVisibility(View.VISIBLE);

        mGridView = (GridView) findViewById(Rx.id.kg_gridview);
        mRechargeAdapter = new RechargeMoneyGridAdapter(mContext, sMoneys,
                RechargeMoneyGridAdapter.UNIT_KUBI);

        mRechargeAdapter.setmMoneyIndex(0);

        mRechargeValue = sMoneys[0] * PayManager.getYoubiRatio();

        mGridView.setAdapter(mRechargeAdapter);

        // 横屏一行显示
        if (SDKControler.getActivityOrientation() == ActivityOrientation.LANDSCAPE) {
            mGridView.setNumColumns(6);
        }

        mGridView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // TODO Auto-generated method stub
                if (mRechargeAdapter.getItem(position) == 0) {
                    return;
                }

                if (!NetWorkUtil.isNetworkAvailable(mContext)) {
                    showToast("请检查您的网络连接");
                    return;
                }

                mInputOtherValueEditText.setText("");
                mInputOtherValueEditText.clearFocus();
                mOtherValueLayout.setVisibility(View.GONE);
                mRechargeAdapter.onItemClick(parent, view, position, id);
                mRechargeAdapter.notifyDataSetChanged();
                mRechargeValue = mRechargeAdapter.getItem(position) * PayManager.getYoubiRatio();
                updateView();

            }

        });

        mOtherValueLayout = (LinearLayout) findViewById(Rx.id.kg_layout_other_money);

        TextView tvOtherNumTip = (TextView) findViewById(Rx.id.kg_pay_other_num_text);
        tvOtherNumTip.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                mRechargeAdapter.setmMoneyIndex(-1);
                mRechargeAdapter.notifyDataSetChanged();
                mOtherValueLayout.setVisibility(View.VISIBLE);
                mInputOtherValueEditText.requestFocus();
                mRechargeValue = getRechargeValueByEditText(mInputOtherValueEditText.getText()
                        .toString());
                updateView();
            }
        });

        mInputOtherValueEditText = (EditText) findViewById(Rx.id.kg_et_custom_num);
        mInputOtherValueEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mOtherValueLayout != null && mOtherValueLayout.getVisibility() == View.VISIBLE) {
                    String value = s.toString().trim();
                    if (AppUtil.checkRechargeValueInput(value)) {

                        mRechargeValue = getRechargeValueByEditText(value);
                        updateView();
                    } else {
                        mRechargeValue = 0;
                        if (!TextUtils.isEmpty(value)) {
                            mInputOtherValueEditText.setText("");
                        }
                    }
                }
            }
        });

        mSubmitRechargeBtn = (Button) findViewById(Rx.id.kg_btn_summit);
        mSubmitRechargeBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkRechargeValue()) {
                    if (mAccountKubiNumber < getFinalRechargeValue()) {
                        Intent intent = new Intent();
                        intent.setClass(mContext, NotEnoughKubiRechargeActivity.class);
                        intent.putExtra(NotEnoughKubiRechargeActivity.ORDER_VALUE,
                                getFixedMoneyNum() > 0 ? getFixedMoneyNum() : mRechargeValue
                                        / PayManager.getYoubiRatio());
                        intent.putExtra(NotEnoughKubiRechargeActivity.ORDER_COUPON, mSelectedCoupon);
                        startActivityForResult(intent, NO_KUBI_RECHARGE_REQUEST_CODE);
                    } else {
                        sendEmptyBackgroundMessage(MSG_REQUEST_PAY_STATUES);
                    }
                }
            }
        });

        mRechargeContent = findViewById(Rx.id.kg_layout_recharge_content);

        mRechargeKubiBtn = (TextView) findViewById(Rx.id.kg_btn_recharge_kubi);

        mKubiRechargeLayout = (RelativeLayout) findViewById(Rx.id.kg_layout_kubi_recharge);
        if (!PayManager.hasYoubiRechargepreferential()) {
            mKubiRechargeLayout.setVisibility(View.GONE);
        } else {
            mRechargeKubiBtn.setText(PayManager.getKubiRechargePreferentialSubTitle());
        }

        mKubiRechargeLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                getActivity().finish();

                Intent intent = new Intent(mContext, RechargeActivity.class);
                intent.putExtra(RechargeActivity.IS_RECHARGE_YOUBI, true);
                intent.putExtra(RechargeActivity.SOURCE_FROM, 3);
                startActivityForResult(intent, KUBI_RECHARGE_REQUEST_CODE);
            }
        });

        updateFixedMoneyNumTextView();
    }

    private int getFinalRechargeValue() {
        int value = mRechargeValue;
        if (getFixedMoneyNum() > 0) {
            value = getFixedMoneyNum() * PayManager.getYoubiRatio();
        }

        if (mSelectedCoupon != null) {
            value -= mSelectedCoupon.getMoney() * PayManager.getYoubiRatio();
            if (value < 0)
                value = 0;
        }

        return value;
    }

    /**
     * 从EditText中获取充值的数值
     * 
     * @param value
     * @return
     */
    private int getRechargeValueByEditText(String value) {
        if (!TextUtils.isEmpty(value)) {
            return Integer.valueOf(value);
        } else {
            return 0;
        }
    }

    @Override
    protected void updateView() {
        updateCouponView(mRechargeValue / PayManager.getYoubiRatio());

        // 游币充值并且有活动的情况下显示提醒活动和代金券只能选一
        if (!mIsRechargeYoubi && !PayManager.showYoubiRechargeCoupon()
                && !PayManager.isCouponInfosRequestFailed()) {
            mCouponLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 根据用户游币数量判断显示内容，定额支付的隐藏支付数额选择，普通支付有游币就显示选择输入界面
     */
    @Override
    protected void updateFixedMoneyNumTextView() {
        if (getFixedMoneyNum() > 0) { // 定额支付
            mRechargeContent.setVisibility(View.GONE);

            // 显示定额充值多少元
            // 游币余额为0时，不显示定额充值多少元
            TextView fixedMoneyNumtTextView = (TextView) findViewById(Rx.id.kg_common_tips_bar_money_num);
            fixedMoneyNumtTextView.setVisibility(View.VISIBLE);

            int value = getFixedMoneyNum() * PayManager.getYoubiRatio();
            if (mSelectedCoupon != null) {
                value = value - mSelectedCoupon.getMoney() * PayManager.getYoubiRatio();
                if (value < 0)
                    value = 0;
            }
            fixedMoneyNumtTextView.setText(Html.fromHtml("<font color=#666666>支付：</font>"
                    + "<font color=#fd9526>" + value + "游币" + "</font>"));

            mRechargeValue = getFixedMoneyNum() * PayManager.getYoubiRatio();
            fixedMoneyNumtTextView.setPadding(0, 0, 0, (int) (20 * getResources()
                    .getDisplayMetrics().density));
        }
    }

    /**
     * 发送取消支付的统计
     */
    private void sendCancelRechargeStatics(String errormsg) {
        sendCancelRechargeStatics(ChargeType.TYPE_KUBI, mRechargeValue, errormsg, 1, errormsg);
    }

    private boolean checkRechargeValue() {

        if (mRechargeValue <= 0) {
            showToast("请输入有效的金额");
            return false;
        }

        if (mRechargeValue % 100 != 0) {
            showToast("请输入100的整倍数金额");
            return false;
        }

        return true;
    }

    private void setKubiValueTextView() {
        mYoubiTextView.setText(Html.fromHtml("<font color=#ff666666>游币余额：</font>"
                + "<font color=#fd9526>"
                + (int) UserManager.getInstance().getCurrentUserInternal().getKubiNum()
                + "游币</font>"));
    }

    @Override
    public void handleBackgroundMessage(Message msg) {
        super.handleBackgroundMessage(msg);

        switch (msg.what) {
            case MSG_BACK_REQUEST_PAY:
                // 游币充值
                // 有支付密码的情况要带上支付密码，没有的话传空。有支付密码框时，不显示页面的loading框，使用密码框的loading；
                // 没有支付密码就使用页面的loading
                if (msg.obj != null) {
                    payByKubi((String) msg.obj);
                } else {
                    sendEmptyUiMessage(MSG_KUBIPAY_ING);
                    payByKubi("");
                }
                break;

            case MSG_REQUEST_PAY_STATUES:
                showLoadingView("网络请求中");
                checkPayPasswdState();
                break;
        }
    }

    @Override
    public void handleUiMessage(Message msg) {
        super.handleUiMessage(msg);
        if (getActivity() == null || getActivity().isFinishing() || isDetached() || !isAdded()) {
            return;
        }
        switch (msg.what) {
            case MSG_KUBIPAY_ING:
                showLoadingView();
                break;
            case MSG_KUBIPAY_SUCCESS:
                // 有支付密码的情况要关闭输入密码框
                if (mInputPayPasswdDialog != null) {
                    mInputPayPasswdDialog.dismiss();
                }

                showRechargeSuccess();

                sendRechargeSuccessEvent(mOrderid, ChargeType.TYPE_KUBI, mRechargeValue);

                // 更新内存的游币余额数量
                UserManager.getInstance().updateYoubiNum();

                break;
            case MSG_KUBIPAY_FAILED:
                hideLoadingView();
                hideSoftInput(getActivity());
                canelRecharge();
                if (mInputPayPasswdDialog != null && msg.obj != null) {
                    mInputPayPasswdDialog.passwdError((String) msg.obj);
                } else if (msg.obj != null && !TextUtils.isEmpty(msg.obj.toString())) {
                    showNoticeDialog(msg.obj.toString());
                } else {
                    ToastUtil.showMsg("支付失败");
                }

                sendCancelRechargeStatics(msg.obj.toString());
                break;

            case MSG_REQUEST_PAY_STATUES_FAILED:
                hideLoadingView();
                showNoticeDialog((String) msg.obj);
                break;

            case MSG_REQUEST_PAY_STATUES_SUCCESS:
                hideLoadingView();
                showInputPayPasswdDialog();
                break;
            default:
                break;
        }
    }

    private void showInputPayPasswdDialog() {
        if (mInputPayPasswdDialog == null) {
            mInputPayPasswdDialog = new InputPayPasswdDialog(getActivity());
        }

        mInputPayPasswdDialog.setPayInfo(AppUtil.getAppName(getActivity()), getFinalRechargeValue()
                + "");
        mInputPayPasswdDialog.setOnPasswordChangedListener(new OnPasswordChangedListener() {
            @Override
            public void onMaxLength(String psw) {
                Message msg = Message.obtain();
                msg.what = MSG_BACK_REQUEST_PAY;
                msg.obj = psw;
                sendBackgroundMessage(msg);
            }

            @Override
            public void onChanged(String psw) {
            }
        });
        mInputPayPasswdDialog.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface arg0) {
                mInputPayPasswdDialog.hideSoftInput();
                mInputPayPasswdDialog = null;
            }
        });

        mInputPayPasswdDialog.show();
    }

    /**
     * 显示一些消息提示的确定弹框
     * 
     * @param tips 弹框Message
     */
    private void showNoticeDialog(String tips) {

        final BaseConfirmDialog failedDialog = new BaseConfirmDialog(getActivity());
        failedDialog.setMessage(TextUtils.isEmpty(tips) ? "" : tips);
        failedDialog.setCancelBtnVisibility(View.GONE);
        failedDialog.setContentGravity(Gravity.CENTER);
        failedDialog.setOKBtnText("知道了");
        failedDialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                failedDialog.dismiss();
            }
        });
        failedDialog.show();
    }

    private void showRechargeComfirmDialog() {

        if (getFinalRechargeValue() == 0) {
            sendEmptyBackgroundMessage(MSG_BACK_REQUEST_PAY);
            return;
        }

        final BaseConfirmDialog dialog = new BaseConfirmDialog(getActivity());
        dialog.setTextPadding(30);
        dialog.setMessage("兑换类型：酷狗游币兑换\n" + "充值游币：" + getFinalRechargeValue() + "游币");
        dialog.setOKClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                dialog.dismiss();
                sendEmptyBackgroundMessage(MSG_BACK_REQUEST_PAY);
            }
        });
        dialog.show();
    }

    /**
     * 游币支付请求
     */
    private void payByKubi(String payPasswd) {
        User user = UserManager.getInstance().getCurrentUserInternal();
        if (user == null) {
            return;
        }
        mOrderid = SDKControler.createNewOrderId();
        KubiPayRequestParams requestParams = new KubiPayRequestParams();

        if (mSelectedCoupon != null) {
            requestParams.setCouponId(mSelectedCoupon.getId());
        }
        requestParams.setMoney(100);
        requestParams.setUserName(user.getAccountName());
        requestParams.setOutOrderId(mOrderid);
        requestParams.setRole(SDKControler.getRoleName());
        requestParams.setExtension1(SDKControler.getExtension1());
        requestParams.setExtension2(SDKControler.getExtension2());
        requestParams.setKugouToken(user.getKugouToken());
        requestParams.setPayPasswd(payPasswd);
        PayManager.payByKubi(requestParams, onKubiPayListener);
    }

    OnKubiPayListener onKubiPayListener = new OnKubiPayListener() {

        @Override
        public void onSuccess(String leftKubi) {
            Message msg = new Message();
            msg.what = MSG_KUBIPAY_SUCCESS;
            msg.obj = leftKubi;
            sendUiMessage(msg);
        }

        @Override
        public void onFailed(String errorMsg) {
            Message msg = new Message();
            msg.what = MSG_KUBIPAY_FAILED;
            msg.obj = errorMsg;
            sendUiMessage(msg);
        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == KUBI_RECHARGE_REQUEST_CODE) {
            User user = UserManager.getInstance().getCurrentUserInternal();
            mAccountKubiNumber = user.getKubiNum();
            if (mAccountKubiNumber < 0) {
                mAccountKubiNumber = 0;
            }
            setKubiValueTextView();

            updateFixedMoneyNumTextView();
        } else if (requestCode == NO_KUBI_RECHARGE_REQUEST_CODE
                && resultCode == NO_KUBI_RECHARGE_RESPONDE_CODE) {
            showRechargeSuccess();
        }
    }

    private void showRechargeSuccess() {
        if (getOnEventListener() != null) {
            getOnEventListener().onRechargeSuccess(ChargeIndexMode.MODE_YOUBI, mRechargeValue);
        }
    }

    private void checkPayPasswdState() {
        CheckPayPasswdStateTask task = new CheckPayPasswdStateTask();
        CheckPayPswStateResponse response = task.request(UserManager.getInstance()
                .getCurrentUserName());
        if (response != null) {
            if (response.isUseful() && response.isPayPasswdSeted() && !response.isLocked()) {
                sendEmptyUiMessage(MSG_REQUEST_PAY_STATUES_SUCCESS);
            } else if (response.isUseful() && !response.isPayPasswdSeted() && !response.isLocked()) {
                hideLoadingView();
                payingWithOutPayPasswd();
            } else {
                Message msg = Message.obtain();
                msg.what = MSG_REQUEST_PAY_STATUES_FAILED;
                msg.obj = response.getPrompt();
                sendUiMessage(msg);
            }
        } else {
            Message msg = Message.obtain();
            msg.what = MSG_REQUEST_PAY_STATUES_FAILED;
            msg.obj = "网络请求失败";
            sendUiMessage(msg);
        }

    }

    private void payingWithOutPayPasswd() {
        showRechargeComfirmDialog();
        // 发送统计--点击确认支付按钮
        sendClickConfirmRechargeBtnStatics(ChargeType.TYPE_KUBI, mRechargeValue);
    }

}
